<!--
@Description:工单抄送
@Author:zqy
@Date:2022-05-24 18:09:30
@Last Modified by:zqy
@Last Modified time:2022-05-24 18:09:30
-->
<template>
  <div :class="$style.carbonCopy">
    <Button :type="!carbonInfo.id || carbonInfo.workOrderState === 3 ? 'info' : 'primary'" :disabled="!carbonInfo.id || carbonInfo.workOrderState === 3 || bottomAuth" @click="openDialog">抄送</Button>
    <el-dialog
      :visible.sync="visible"
      width="80%"
      title="抄送"
      destroy-on-close
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <div>
        <el-form
          ref="form"
          :model="formData"
          :rules="formRules"
          label-width="110px"
        >
          <el-row>
            <el-col v-if="!officeDispach" :span="24">
              <el-form-item
                prop="officeCode"
                label="抄送办事处："
                style="width:50%"
              >
                <SearchSelectPicker
                  url="/call-center/api/v1/mscInfo/office/ref/page"
                  placeholder="请选择"
                  lable-name="name"
                  value-name="code"
                  method="get"
                  :value.sync="formData.officeCode"
                  :lable.sync="formData.officeName"
                ></SearchSelectPicker>
                <!-- @selectChange="resetDisName" -->
              </el-form-item>
            </el-col>
            <template v-if="!disDispach">
              <el-col :span="6">
                <el-form-item prop="disCode" label="抄送经销商：">
                  <SearchSelectPicker
                    url="/call-center/api/v1/mscInfo/dealer/ref/page"
                    method="get"
                    placeholder="请选择经销商"
                    :params="{query:{officeCode:formData.disOfficeCode},type:0}"
                    lable-name="name"
                    value-name="code"
                    custom-name="codeOrName"
                    :parent-id="formData.officeCode"
                    :value.sync="formData.disCode"
                    :lable.sync="formData.disName"
                    :current-id.sync="formData.disId"
                    clearable
                    @selectChange="disSelectChange"
                  ></SearchSelectPicker>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item prop="disCode" label="所属办事处：" label-width="140px">
                  <SearchSelectPicker
                    url="/call-center/api/v1/mscInfo/office/ref/page"
                    placeholder="请选择"
                    lable-name="name"
                    value-name="code"
                    method="get"
                    :value.sync="formData.disOfficeCode"
                    :lable.sync="formData.disOfficeName"
                    @selectChange="resetDisName"
                  ></SearchSelectPicker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  prop="shopCode"
                  label="门店："
                  :rules="[
                    {required:false,message:'请选择门店',trigger:'change'}
                  ]"
                >
                  <SearchSelectPicker
                    url="/call-center/api/v1/mscInfo/shop/page"
                    placeholder="请选择"
                    lable-name="shopName"
                    value-name="shopCode"
                    custom-name="customerName"
                    :remote="false"
                    :params="{query:{businessStatus: '1,2,6',status:1,customerCodes: formData.disCode},type:1}"
                    :must-pid="true"
                    :parent-id="formData.disCode"
                    :value.sync="formData.shopCode"
                    :lable.sync="formData.shopName"
                    @selectChange="shopSelectChange"
                  ></SearchSelectPicker>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item prop="afterSalesCall" label="售后联系人电话：" label-width="140px">
                  <el-autocomplete
                    v-model="formData.afterSalesCall"
                    placeholder="请输入售后联系人电话"
                    popper-class="my-autocomplete"
                    :popper-append-to-body="false"
                    clearable
                    :fetch-suggestions="afterCallSearchAsync"
                    style="width:100%"
                  >
                    <template slot-scope="{ item }">
                      <div class="tel" style="font-size: 12px">{{ item.value }}</div>
                      <span class="name">{{ item.name }}</span>
                    </template>
                    <template slot="append">
                      <svg-icon icon-class="shouji-solid" class="sms" @click="toSms(formData)"></svg-icon>
                      <SvgIcon icon-class="dianhuaboda-solid" style="color:#00926d;cursor:pointer;" @click.native.stop="callOutHandle(formData.afterSalesCall)"></SvgIcon>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
            </template>
            <el-col :span="24">
              <el-form-item prop="" label="接收岗位:" label-width="100px">
                <div class="post-wrap">
                  <ReceivePost v-model="handlerPosts" is-carbon-copy :work-order-id="carbonInfo.id"></ReceivePost>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="dutyDepts" label="">
                <div slot="label">
                  责任部门：
                  <div style="text-align:right"><DepartReciverDispatch ref="refRec" text="添加" title="选择抄送接收人" :button-auth="true" :enable-open="dispatchcOrderEnableOpen" @select-change="submitReciverChange" /></div>
                </div>
                <table-box
                  ref="refTable"
                  table-size="small"
                  :table-config="tableConfig"
                  :table-height="300"
                  :data="deptData"
                  no-request
                  :show-index="false"
                  :show-selection="false"
                  :show-custom-setting="false"
                  :table-sortable="false"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item align="right">
            <Button @click="closeDialog">取消</Button>
            <Button type="primary" :loading="handleLoading" @click="submitHandle">确定抄送</Button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchSelectPicker from '@/components/SearchSelectPicker'
import Button from '@/components/Button'
import DepartReciverDispatch from '../createOrder/components/DepartReciverDispatch'
import ReceivePost from './ReceivePost'
import { postCarbonCopy } from '@/api/workOrder'
import { getMscInfoShop } from '@/api/mscInfo'
import { getShopAfterInfo } from '@/api/shopAfter'
import { getWorkOrderOperationReceiverList } from '@/api/workOrderOperationReceiver'
import { ArrayFormat } from '@/utils/params-format'
const validteShopCode = { required: true, message: '门店不能为空', trigger: 'change' }
export default {
  name: 'CarbonCopy',
  components: {
    SearchSelectPicker,
    Button,
    DepartReciverDispatch,
    ReceivePost
  },
  props: {
    ccSystem: {
      type: Array,
      default: () => ([])
    }, // 抄送系统
    carbonInfo: {
      type: Object,
      default: () => ({})
    },
    bottomAuth: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      handleLoading: false,
      officeDispach: false, // 办事处是否已指派
      disDispach: false, // 经销商是否已指派
      formData: {
        officeCode: '', // 派单办事处编码
        officeName: '', // 办事处
        disId: '', // 派单经销商ID
        disCode: '', // 经销商编码
        disName: '', // 经销商
        disOfficeCode: '', // 派单经销商对应办事处
        disOfficeName: '', // 派单经销商对应办事处
        shopCode: '', // 门店编码
        shopName: '', // 门店
        afterSalesCall: ''
      },
      shopCallTel: [],
      handlerPosts: [], // 接收人岗位
      formRules: {
        shopCode: {}
      },
      deptData: [],
      patchDept: [], // 派送责任人
      tableConfig: {
        interfacePath: ``,
        tabIndex: 40,
        hideFuncBar: true,
        // sort: 'createTime',
        order: 'desc',
        setting: [
          {
            prop: 'deptName',
            label: '责任部门',
            minWidth: 150
          },
          {
            prop: 'organizationName',
            label: '组织',
            minWidth: 150,
            formatData: ({ qupOrganizationName, organizationName }) => {
              return organizationName || qupOrganizationName
            }
          },
          {
            prop: 'receiver',
            label: '用户',
            minWidth: 150,
            formatData: ({ receiver, receiverName }) => {
              return ` ${receiverName}(${receiver})`
            }
          },
          {
            prop: 'receiverPhone',
            label: '联系电话',
            minWidth: 150
          },
          {
            prop: 'postName',
            label: '岗位',
            minWidth: 150
          },
          /* {
            prop: 'remark',
            label: '备注',
            minWidth: 150
          }, */
          {
            prop: 'state',
            label: '接收状态',
            width: 80,
            formatData: ({ state }) => {
              return state === '02' ? '已接收' : '未接收'
            }
          },
          {
            prop: '',
            label: '操作',
            minWidth: 80,
            fixed: 'right',
            align: 'center',
            render: (_, rows) => {
              return (
                <el-button size='small' type='text' size='mini' onClick={this.handleDelete.bind(this, rows)}>删除</el-button>
              )
            }
          }
        ]
      }
    }
  },
  methods: {
    async openDialog() {
      await this.getDeptTableData()
      this.$nextTick(() => {
        this.visible = true
      })
    },
    /**
     * 弹窗关闭时触发
     */
    closeDialog() {
      this.resetData()
      this.visible = false
    },
    resetData() {
      this.officeDispach = false
      this.disDispach = false
      this.deptData = []
      this.formData = {
        officeCode: '', // 派单办事处编码
        officeName: '', // 办事处
        disId: '', // 派单经销商ID
        disCode: '', // 经销商编码
        disName: '', // 经销商
        disOfficeCode: '', // 派单经销商对应办事处
        disOfficeName: '', // 派单经销商对应办事处
        shopCode: '', // 门店编码
        shopName: '', // 门店
        afterSalesCall: ''
      }
      this.shopCallTel = []
      this.handleLoading = false
    },
    dispatchcOrderEnableOpen() {
      return new Promise((resolve, reject) => {
        return resolve()
      })
    },
    async getDeptTableData() {
      // 查询经销商和办事处是否指派
      getWorkOrderOperationReceiverList({ workOrderId: this.carbonInfo.id, operationType: '01' }).then(res => {
        if (res.data) {
          if (res.data['01']) {
            // 办事处指派
            this.officeDispach = true
          }
          if (res.data['02']) {
            // 经销商指派
            this.disDispach = true
          }
          this.patchDept = res.data['03'] || []
        }
      })
      getWorkOrderOperationReceiverList({ workOrderId: this.carbonInfo.id, operationType: '02' }).then(res => {
        if (res.data) {
          const officeData = res.data['01'] || '' // 办事处
          const disData = res.data['02'] || '' // 经销商
          this.deptData = res.data['03'] || [] // 责任部门
          if (officeData && officeData.dept) {
            // 办事处
            this.$set(this.formData, 'officeCode', officeData.dept)
            this.$set(this.formData, 'officeName', officeData.deptName)
          }
          if (disData && disData.dept) {
            // 经销商
            this.$set(this.formData, 'disCode', disData.dept)
            this.$set(this.formData, 'disName', disData.deptName)

            this.$set(this.formData, 'disOfficeCode', disData.organization)
            this.$set(this.formData, 'disOfficeName', disData.organizationName)

            this.$set(this.formData, 'shopCode', disData.shopCode)
            this.$set(this.formData, 'shopName', disData.shopName)

            this.$set(this.formData, 'afterSalesCall', disData.receiverPhone)
          }
        }
      })

      /* const filtersRaw = [
        { id: 'operationType', property: 'operationType', operator: '=', value: '02' }, // 操作类型(01:派单;02:抄送)
        // { id: 'operationMode', property: 'operationMode', operator: '=', value: '03' }, // 操作模式(01:办事处;02:经销商;03:责任部门;)
        { id: 'workOrderId', property: 'workOrderId', operator: '=', value: this.carbonInfo.id }
      ]

      const params = new FormData()
      params.append('pageFlag', false)
      params.append('filtersRaw', JSON.stringify(filtersRaw))
      await getWorkOrderOperationReceiverPage(params).then(res => {
        const data = res.data && res.data.records || []
        this.deptData = data.filter(v => v.operationMode === '03') // 责任部门
        const officeData = data.filter(v => v.operationMode === '01') // 办事处
        const disData = data.filter(v => v.operationMode === '02') // 经销商
        if (officeData.length > 0) {
          // 办事处
          const obj = officeData[0]
          this.$set(this.formData, 'officeCode', obj.dept)
          this.$set(this.formData, 'officeName', obj.deptName)
          // this.$set(this.formData, 'afterSalesCall', obj.receiverPhone)
        }
        if (disData.length > 0) {
          // 经销商
          const obj = disData[0]
          this.$set(this.formData, 'disCode', obj.dept)
          this.$set(this.formData, 'disName', obj.deptName)

          this.$set(this.formData, 'disOfficeCode', obj.organization)
          this.$set(this.formData, 'disOfficeName', obj.organizationName)

          this.$set(this.formData, 'shopCode', obj.shopCode)
          this.$set(this.formData, 'shopName', obj.shopName)

          this.$set(this.formData, 'afterSalesCall', obj.receiverPhone)
        }
      }) */
    },
    /**
     * 重置经销商以下相关信息
     */
    resetDisName() {
      this.$set(this.formData, 'disCode', '')
      this.$set(this.formData, 'disName', '')
      this.$set(this.formData, 'shopCode', '')
      this.$set(this.formData, 'shopName', '')
      this.$set(this.formData, 'afterSalesCall', '')
      this.shopCallTel = []
      Object.assign(this.formRules, { shopCode: {}})
      setTimeout(() => { this.$refs.form.validateField(['shopCode']) }, 0)
    },
    // 经销商值改变时
    disSelectChange(data) {
      this.$set(this.formData, 'shopCode', '')
      this.$set(this.formData, 'shopName', '')
      this.$set(this.formData, 'disOfficeCode', '')
      this.$set(this.formData, 'disOfficeName', '')
      this.$set(this.formData, 'afterSalesCall', '')
      this.shopCallTel = []
      Object.assign(this.formRules, { shopCode: {}})
      setTimeout(() => { this.$refs.form.validateField(['shopCode']) }, 0)
      if (data && data.code) {
        this.$set(this.formData, 'disId', data.id)
        this.$set(this.formData, 'disOfficeCode', data.organizationCode)
        this.$set(this.formData, 'disOfficeName', data.organizationName)
        this.checkShopNum(data.code)
      }
    },
    shopSelectChange(data) {
      if (data && data.shopCode) this.getSalesCall({ shopCode: data.shopCode })
    },
    // 查询该经销商下是否有门店
    checkShopNum(disCode) {
      const params = new FormData()
      params.append('page', 1)
      params.append('rows', 2)

      getMscInfoShop({ customerCodes: disCode }, params).then(res => {
        if (res.success === 1) {
          if (res.data.total === 0) {
            this.getSalesCall({ disCode: this.formData.disCode })
            Object.assign(this.formRules, { shopCode: validteShopCode })
            setTimeout(() => { this.$refs.form.validateField(['shopCode']) }, 0)
          }
        }
      })
    },
    /**
     * 获取门店对应的联系方式
     */
    getSalesCall(obj) {
      if (Object.keys(obj).length === 0) {
        return
      }
      this.shopCallTel = []
      const paramsArr = ArrayFormat(obj)
      const pageInfo = new FormData()
      pageInfo.append('rows', 20)
      pageInfo.append('page', 1)
      if (Array.isArray(paramsArr) && paramsArr.length) pageInfo.append('filtersRaw', JSON.stringify(paramsArr))
      getShopAfterInfo(pageInfo).then(res => {
        if (res.success === 1) {
          const data = res.data.records
          data.forEach((item, index) => {
            if (item.contactPhone) {
              item.value = item.contactPhone
              item.name = item.afterSaleContact
            } else {
              data.splice(index, 1)
            }
          })
          if (Array.isArray(data) && data.length === 1) {
            this.formData.afterSalesCall = data[0].value
          }
          this.shopCallTel = data
        } else {
          this.shopCallTel = []
        }
      })
    },
    /**
     * 匹配门店相应的联系方式
     */
    afterCallSearchAsync(queryString, callback) {
      const shopCallTel = this.shopCallTel
      const results = queryString ? shopCallTel.filter(this.createStateFilter(queryString)) : shopCallTel

      callback(results)
    },
    /**
     * JS-filter Function
     */
    createStateFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 短信发送
    toSms(row) {
      const callTel = (row.afterSalesCall || '').trim()
      const provinceName = this.carbonInfo.provinceName || ' '
      const cityName = this.carbonInfo.cityName || ' '
      const countyName = this.carbonInfo.countyName || ' '
      const streetName = this.carbonInfo.streetName || ' '
      const detailAddress = this.carbonInfo.detailAddress || ' '
      const contactName = this.carbonInfo.contactName || ' '
      const contactPhone = this.carbonInfo.contactPhone || ' '
      const workOrderCode = this.carbonInfo.workOrderCode || ' '
      const content = `工单编号：${workOrderCode}，客户姓名：${contactName}，联系电话：${contactPhone}，客户地址：${provinceName}${cityName}${countyName}${streetName}${detailAddress}`
      if (!callTel) {
        this.$message.info('请输入电话号码！')
        return
      }
      this.$router.push({ name: 'SMSSend', query: { callTel, workOrderCode, content }})
    },
    // 外呼
    callOutHandle(phone) {
      if (!phone) {
        this.$message.info('没有电话号码！')
        return
      }
      this.$refs.callOut.debounceCallOut(phone)
    },
    // 删行
    handleDelete(row) {
      const index = row.keyIndex
      this.deptData.splice(index, 1)
    },
    submitReciverChange(receiverList) {
      if (receiverList.length > 0) {
        const excludes = receiverList.filter(item => {
          const flag = this.patchDept.some(v => v.receiver === item.receiver)
          return flag
        })
        if (excludes.length > 0) {
          const names = excludes.map(v => v.receiverName)
          this.$message.warning(`${names.join(',')}已指派，不能抄送`)
          return
        }
      }
      this.$refs.refRec.closeDialog()
      if (this.deptData.length === 0) {
        this.deptData = receiverList
        return
      }
      receiverList.forEach(item => {
        const index = this.deptData.findIndex(v => v.receiver === item.receiver)
        if (index === -1) {
          this.deptData.push(item)
        }
      })
    },
    submitHandle() {
      if (this.handleLoading) return
      /* const params = this.getParams()
      Object.keys(params).forEach(k => {
        if (params[k] === 'undefined' || params[k] === undefined || params[k] === '') delete params[k]
      })
      if (params.hasOwnProperty('disCode') && params.hasOwnProperty('disName')) {

      }
      */
      const receiveSystem = [] // 接收系统
      const sysNames = [] // 接受系统名称
      const respDepart = [] // 责任部门名称集合
      let dtoList = []
      const { officeCode, officeName, disOfficeCode, disOfficeName, disCode, disName, shopCode, shopName, afterSalesCall } = this.formData
      const workOrderId = this.carbonInfo.id

      if (officeCode && officeName) {
        // 办事处
        receiveSystem.push('UIP')
        sysNames.push('办事处')
        const obj = {
          workOrderId,
          operationMode: '01',
          operationType: '02',
          dept: officeCode,
          deptName: officeName
        }
        dtoList.push(obj)
      }

      if (disCode && disName) {
        // 改派经销商
        /* if (!shopCode || !shopName) {
          this.$message.warning('派单经销商门店不能为空')
          return
        } */
        receiveSystem.push('PANDA')
        sysNames.push('经销商')
        const obj = {
          workOrderId,
          operationMode: '02',
          operationType: '02',
          dept: disCode,
          deptName: disName,
          organization: disOfficeCode,
          organizationName: disOfficeName,
          shopCode: shopCode,
          shopName: shopName
        }
        dtoList.push(obj)
      }

      if (this.deptData.length > 0) {
        // 责任部门
        receiveSystem.push('ECO')
        sysNames.push('责任部门')
        const tmpArr = this.deptData.map(v => {
          const i = respDepart.findIndex(r => r === v.deptName)
          if (i === -1) {
            respDepart.push(v.deptName)
          }
          return {
            workOrderId,
            operationMode: '03',
            operationType: '02',
            dept: v.dept,
            deptName: v.deptName,
            organization: v.organization || v.qupOrganization,
            organizationName: v.organizationName || v.qupOrganizationName,
            receiver: v.receiver,
            receiverName: v.receiverName,
            receiverPhone: v.receiverPhone,
            postCode: v.postCode,
            postName: v.postName
          }
        })
        dtoList = [...dtoList, ...tmpArr]
      }

      if (dtoList.length === 0) {
        this.$message({
          // message: '请至少指派【经销商、办事处、责任部门】其中一个',
          message: '指派单位不能为空',
          type: 'warning'
        })
        return
      }

      if (afterSalesCall) {
        const phone = afterSalesCall.trim()
        const reg = /^1\d{10,11}$/
        if (phone.length !== 11 && !reg.test(phone)) {
          this.$message({
            message: '售后联系电话格式错误',
            type: 'warning'
          })
          return
        }
      }
      this.$msgbox({
        title: '抄送',
        showCancelButton: true,
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        message: `确认抄送此工单给当前指定的【${sysNames.join(',')}】吗?`,
        type: 'warning'
      }).then(() => {
        this.handleLoading = true
        postCarbonCopy(workOrderId, dtoList).then(res => {
          this.handleLoading = false
          if (res.success === 1) {
            this.$message({
              message: '工单抄送成功',
              type: 'success'
            })
            this.$emit('on-success')
            this.closeDialog()
          }
        }, () => {
          this.handleLoading = false
          /* this.$message({
            type: 'warning',
            message: '工单抄送失败'
          }) */
        })
      }).catch(() => {})
    },

    getParams() {
      const { officeCode, officeName, disCode, disName, shopCode, shopName, afterSalesCall } = this.formData
      const { nextHandler, nextHandlerName, overdueReason, patchCode, processRate, processingDeadline, urgencyCause, urgencyDegree } = this.carbonInfo
      const params = {
        id: this.id,
        officeCode,
        officeName,
        shopCode,
        shopName,
        disCode,
        disName,
        afterSalesCall,

        nextHandler,
        nextHandlerName,
        overdueReason,
        patchCode,
        processRate,
        processingDeadline,
        urgencyCause,
        urgencyDegree
      }
      return params
    }
  }
}
</script>
<style lang="scss" module>
.carbonCopy{
  display: inline-block;
}

</style>
<style lang="scss" scoped>
// 短信图标
.sms{
  color:#00926d;
  cursor: pointer;
}
.post-wrap{
  padding: 5px 0;
}
</style>
